package com.example.wifi_test;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.widget.Toast;

import java.util.List;

/**
 * WIFIUtils类
 */
class WIFIUtils {
    private final WifiManager wifi;
    private final Context ct;

    WIFIUtils(Context context) {
        ct = context;
        wifi = (WifiManager) ct.getSystemService(Context.WIFI_SERVICE);
    }

    private static boolean isHexWepKey(String wepKey) {
        final int len = wepKey.length();

        // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?)
        if (len != 10 && len != 26 && len != 58) {
            return false;
        }

        return isHex(wepKey);
    }

    private static boolean isHex(String key) {
        for (int i = key.length() - 1; i >= 0; i--) {
            final char c = key.charAt(i);
            if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a'
                    && c <= 'f')) {
                return false;
            }
        }

        return true;
    }

    /**
     * 生成wifi连接配置
     *
     * @param SSID     名称
     * @param Password 密码
     * @param Type     加密类型 wpa wep 无
     * @return wifi配置
     */
    private WifiConfiguration createWifiInfo(String SSID, String Password,
                                             String Type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";
        // nopass
        if (Type.equals("NONE")) {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        }
        // wep
        if (Type.equals("WEP")) {
            if (!Password.isEmpty()) {
                if (isHexWepKey(Password)) {
                    config.wepKeys[0] = Password;
                } else {
                    config.wepKeys[0] = "\"" + Password + "\"";
                }
            }
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        // wpa
        if (Type.equals("WPA")) {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.TKIP);
            // 此处需要修改否则不能自动重联
            // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }
        return config;
    }
    public void forget(String ssid){
        List<WifiConfiguration> conf = wifi.getConfiguredNetworks();
        for (WifiConfiguration c : conf){
            if (c.SSID.replace("\"", "").equals(ssid)){
                wifi.removeNetwork(c.networkId);
                break;
            }
        }

    }

    /**
     * 检查是否连接过
     * @param ssid wifi名称
     * @return 是否存在
     */
    public boolean isSave(String ssid){
        try {
            List<WifiConfiguration> conf = wifi.getConfiguredNetworks();
            for (WifiConfiguration c : conf){
                if (c.SSID.replace("\"", "").equals(ssid)){
                    return true;
                }
            }
            return false;
        }catch (Exception e){
            return false;
        }
    }
    /**
     * 连接指定wifi
     *
     * @param ssid 名称
     * @param pswd 密码
     */
    public void connect(String ssid, String pswd) {
        //先断开
        WifiInfo info = wifi.getConnectionInfo();
        wifi.disableNetwork(info.getNetworkId());
        wifi.disconnect();
        //已经连接过
        int curID = 0;
        List<WifiConfiguration> conf = wifi.getConfiguredNetworks();
        for (WifiConfiguration c : conf) {
            if (c.SSID.replace("\"", "").equals(ssid)) {
                curID = c.networkId;
                boolean ok = wifi.enableNetwork(c.networkId, true);
                WifiInfo cInfo = wifi.getConnectionInfo();
                if(cInfo.getBSSID()==null){

                    Log.e("wifi", ssid+":已失效");
                }

                break;
            }
        }
        String type = "NONE";
        //连接扫描到的wifi
        WifiConfiguration config = new WifiConfiguration();
        for (ScanResult sr : wifi.getScanResults()) {
            if (!sr.SSID.equals(ssid)) {
                //直接在扫描到的连接里查找
                continue;
            }
            //System.out.println(sr.capabilities);
            if (sr.capabilities.contains("WPA")) {
                type = "WPA";
                //密码为WPA。
            } else if (sr.capabilities.contains("WEP")) {
                type = "WEP";
                //WEP
            } else {
                type = "NONE";
                //无密码
            }
            break;
        }
        boolean ok;
        if(curID==0){
            int id = wifi.addNetwork(createWifiInfo(ssid, pswd, type));
            ok = wifi.enableNetwork(id, true);
            Log.e("wifi", "连接" + ok);
        }
        ok = wifi.reconnect();
        Log.e("wifi", "重新连接" + ok);
        if (!ok) {
            showMsg("wifi连接失败！");
        }
    }

    /**
     * 提示信息
     *
     * @param msg 信息
     */
    private void showMsg(String msg) {
        Toast.makeText(ct, msg, Toast.LENGTH_LONG).show();
    }

    /**
     * 扫描WIFI
     */
    public void scan(BroadcastReceiver br) {

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        ct.registerReceiver(br, intentFilter);

        try {

            if (!wifi.isWifiEnabled()) {
                wifi.setWifiEnabled(true);
            }

            boolean success = wifi.startScan();

            if (!success) {
                //失败
                showMsg("扫描失败,请检查定位权限！");
                Log.e("WIFI", "扫描失败,请检查定位权限！");
            }
        } catch (Exception e) {
            showMsg("扫描失败,请检查权限以及在Android 8以上使用");
            Log.e("WIFI", "扫描失败,请检查权限以及在Android 8以上使用");
        }
    }

    /**
     * 获取扫描列表
     *
     * @return 列表
     */
    public List<ScanResult> getList() {
        return wifi.getScanResults();
    }

    public List<WifiConfiguration> getConfig() {

        return wifi.getConfiguredNetworks();
    }

    public int calculateSignalLevel(int l, int nl) {
        return WifiManager.calculateSignalLevel(l, nl);
    }

    public WifiInfo getConnectionInfo() {
        return wifi.getConnectionInfo();

    }
}
